package com.ruoyi.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.ParkingInfo;
import com.ruoyi.domain.ParkingWhite;
import com.ruoyi.mapper.ParkingInfoMapper;
import com.ruoyi.wss.WebSocketMessageService;
import com.ruoyi.wss.dahua.Enum.MasWebsocketEnum;
import com.ruoyi.wss.dahua.config.DaHuaConfig;
import com.ruoyi.wss.dahua.request.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mapper.ParkingBlackMapper;
import com.ruoyi.domain.ParkingBlack;
import com.ruoyi.service.IParkingBlackService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 黑名单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-04
 */
@Slf4j
@Service
public class ParkingBlackServiceImpl implements IParkingBlackService 
{
    @Resource
    private ParkingBlackMapper parkingBlackMapper;
    @Resource
    private ParkingInfoMapper parkingInfoMapper;
    @Autowired
    private WebSocketMessageService webSocketMessageService;

    /**
     * 查询黑名单
     * 
     * @param blackId 黑名单主键
     * @return 黑名单
     */
    @Override
    public ParkingBlack selectParkingBlackByBlackId(Long blackId)
    {
        return parkingBlackMapper.selectParkingBlackByBlackId(blackId);
    }

    /**
     * 查询黑名单列表
     * 
     * @param parkingBlack 黑名单
     * @return 黑名单
     */
    @Override
    public List<ParkingBlack> selectParkingBlackList(ParkingBlack parkingBlack)
    {
        return parkingBlackMapper.selectParkingBlackList(parkingBlack);
    }

    /**
     * 新增黑名单
     * 
     * @param parkingBlack 黑名单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertParkingBlack(ParkingBlack parkingBlack)
    {
        ParkingBlack query = new ParkingBlack();
        query.setCarNum(parkingBlack.getCarNum());
        List<ParkingBlack> list = parkingBlackMapper.selectParkingBlackList(query);
        if (list.size() > 0){
            throw new RuntimeException("车牌已存在");
        }
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingBlack.getParkId());
        if (Objects.isNull(parkingInfo)){
            throw new RuntimeException("未查询到停车场信息");
        }
        Boolean result = sendBlackRequest(DaHuaConfig.BLACK_ADD, parkingBlack, parkingInfo);
        if(result){
            parkingBlack.setIssuanceStatus("1");
        }else {
            parkingBlack.setIssuanceStatus("0");
        }
        parkingBlack.setCreateBy(getUsername());
        parkingBlack.setCreateTime(DateUtils.getNowDate());
        parkingBlack.setDeptId(parkingInfo.getDeptId());
        parkingBlack.setDelFlag("0");
        parkingBlackMapper.insertParkingBlack(parkingBlack);
        return 1;
    }

    /**
     * 修改黑名单
     * 
     * @param parkingBlack 黑名单
     * @return 结果
     */
    @Override
    public int updateParkingBlack(ParkingBlack parkingBlack)
    {
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingBlack.getParkId());
        if (Objects.isNull(parkingInfo)){
            throw new RuntimeException("未查询到停车场信息");
        }

        Boolean result = sendBlackRequest(DaHuaConfig.BLACK_UPDATE, parkingBlack, parkingInfo);
        if(result){
            parkingBlack.setIssuanceStatus("1");
        }else {
            parkingBlack.setIssuanceStatus("0");
        }
        parkingBlack.setUpdateBy(getUsername());
        parkingBlack.setUpdateTime(DateUtils.getNowDate());
        parkingBlack.setDeptId(parkingInfo.getDeptId());
        parkingBlack.setDelFlag("0");
        parkingBlackMapper.updateParkingBlack(parkingBlack);
        return 1;
    }

    /**
     * 批量删除黑名单
     * 
     * @param blackIds 需要删除的黑名单主键
     * @return 结果
     */
    @Override
    public int deleteParkingBlackByBlackIds(Long[] blackIds)
    {
        return parkingBlackMapper.deleteParkingBlackByBlackIds(blackIds);
    }

    /**
     * 删除黑名单信息
     * 
     * @param blackId 黑名单主键
     * @return 结果
     */
    @Override
    public int deleteParkingBlackByBlackId(Long blackId)
    {
        ParkingBlack parkingBlack = parkingBlackMapper.selectParkingBlackByBlackId(blackId);
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingBlack.getParkId());
        Boolean res = sendBlackRequest(DaHuaConfig.BLACK_DELETE, parkingBlack, parkingInfo);
        if(res){
            parkingBlackMapper.deleteParkingBlackByBlackId(blackId);
        }else {
            throw new RuntimeException("下发删除指令失败，删除失败");
        }
        return 1;
    }

    @Override
    public int sendRequest(ParkingBlack parkingBlack) {
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingBlack.getParkId());
        if (Objects.isNull(parkingInfo)){
            throw new RuntimeException("未查询到停车场信息");
        }
        Boolean result = sendBlackRequest(DaHuaConfig.BLACK_ADD, parkingBlack, parkingInfo);
        if(result){
            parkingBlack.setIssuanceStatus("1");
            return parkingBlackMapper.updateParkingBlack(parkingBlack);
        }else {
            throw new RuntimeException("重新下发指令失败！");
        }

    }


    /**
     * 车辆黑名单请求
     * @param operateType
     * @param parkingBlack
     * @param parkingInfo
     * @return
     */
    public Boolean sendBlackRequest(Integer operateType, ParkingBlack parkingBlack, ParkingInfo parkingInfo){
        log.info("车辆黑名单请求JSON：{}", parkingBlack);
        String platformId = parkingInfo.getPlatformId();
        // 组装请求参数
        ParkingBlackRequest  parkingBlackRequest = ParkingBlackRequest.builder()
                .parkingLotCodes(parkingInfo.getParkCode())
                .carNum(parkingBlack.getCarNum())
                .licensePlateColor(parkingBlack.getCarNumColor().intValue())
                .carOwner(parkingBlack.getOwner())
                .phone(parkingBlack.getOwnerTel())
                .operateTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,DateUtils.getNowDate()))
                .isNewEnergy(Integer.valueOf(parkingBlack.getIsNewEnergy()))
                .reason(parkingBlack.getReason())
                .build();
        List<ParkingBlackRequest> list = new ArrayList<>();
        list.add(parkingBlackRequest);

        ParkingBlackListRequest parkingBlackListRequest = new ParkingBlackListRequest();
        parkingBlackListRequest.setPlatformId(platformId);
        parkingBlackListRequest.setOperateType(operateType);
        parkingBlackListRequest.setBlackType(Integer.valueOf(parkingBlack.getBlackType()));
        parkingBlackListRequest.setBlackList(list);

        // 发送请求
        RequestData<ParkingBlackListRequest> requestData = new RequestData<>(
                MasWebsocketEnum.BLACK_CAR_SYNC.getMethod(), parkingBlackListRequest);
        CommonRequest<ParkingBlackListRequest> commonRequest = new CommonRequest<>("transform", 1, requestData);
        log.info("车辆黑名单请求JSON：{}", parkingBlackRequest);
        try {
            Boolean result = webSocketMessageService.operationDevice(platformId, commonRequest);
            if(!result){
                log.error("车辆黑名单失败：{}，下级平台：{}", parkingBlack, platformId);
                return false;
            }else{
                log.info("车辆黑名单成功：{}，下级平台：{}", parkingBlack, platformId);
                return true;
            }
        } catch (Exception ex) {
            log.error("车辆黑名单失败：{}，下级平台：{}", ex.getMessage(), platformId);
//            throw new RuntimeException("车辆黑名单失败");
            return false;
        }
    }
}
